import requests
import logging
from utils.substitution_tool import var_substitution, parameter_substitution
from utils.global_variable_tool import gv  # 导入 GlobalVariable 类

logger = logging.getLogger(__name__)

class RequestTool:
    def __init__(self, env_host_port):
        self.env_host_port = env_host_port

    def send_request(self, casedata):
        headers = casedata["request"]["headers"]
        method = casedata["request"]["method"]
        url = self.env_host_port + casedata["request"]["url"]
        params = casedata["request"]["params"]

        if headers:
            headers = parameter_substitution(str(headers))
            headers = eval(headers)

        if params:
            params = parameter_substitution(str(params))
            params = var_substitution(params)
            params = eval(params)
        logger.info(">>>>>params:{}".format(params))

        try:
            if method.upper() == 'GET':
                res = requests.get(url=url, headers=headers, params=params, timeout=10)
                logger.info("执行请求后，结果是：%s" % res.text)
            elif method.upper() == 'POST':
                res = requests.post(url=url, headers=headers, json=params, timeout=10)
                logger.info("执行请求后，结果是：%s" % res.text)
            else:
                logger.error("不支持的请求方法: %s" % method)
                raise ValueError("不支持的请求方法: %s" % method)
        except Exception as e:
            logger.error('出错了，错误是%s' % e)
            raise e

        # 获取全局变量
        global_vars = gv.getVars()
        logger.info("当前全局变量：{}".format(global_vars))

        return res